package com.fivestar.pmanager.web.controller;

import com.fivestar.pmanager.core.util.CodeHelper;
import com.fivestar.pmanager.model.SysModuleBean;
import com.fivestar.pmanager.service.SysModuleService;
import com.fivestar.pmanager.web.vo.TreeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 登录控制器
 */
@SuppressWarnings("all")
@Controller("loginController")
public class LoginController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private SysModuleService moduleService;

    @RequestMapping("login")
    public ModelAndView login(HttpServletRequest request)
    {
    	logger.info("{}=== PLEASE LOGIN");
        return new ModelAndView("login");
    }


    @RequestMapping("logout")
    public ModelAndView logout(HttpSession session)
    {
    	logger.info("{}=== LOGOUT " + session.getId());
        session.invalidate();
        return new ModelAndView("login");
    }


    @RequestMapping("sessiontimeout")
    public void sessionTimeout(HttpServletResponse response)
    {
        try
        {
            ServletOutputStream output = response.getOutputStream();
            output.print("<script>window.parent.location='login.do'</script>");
        }
        catch (Exception e)
        {

        }
    }


    @RequestMapping("welcome")
    public ModelAndView welcome(HttpServletRequest request)
    {
        List<SysModuleBean> modules = moduleService.getUserModule(getCurrUser().getRowId());
        List<TreeModule> menus = initModuleTree(modules);
        request.getSession().setAttribute("menus", menus);
        return new ModelAndView("welcome");
    }
    
    @RequestMapping("accessDefine")
    public ModelAndView accessDefine(HttpServletRequest request)
    {
    	return new ModelAndView("accessDefine");
    }


    /**
     * 初始化菜单
     *
     * @param modules
     */
    private List<TreeModule> initModuleTree(List<SysModuleBean> modules)
    {
        List<TreeModule> root = new ArrayList<>();
        for (SysModuleBean module : modules)
        {
            if(module.getParentId() == null || module.getParentId().equals("-1"))
            {
                root.add(new TreeModule(
                                module.getRowId(),
                                module.getModuleName(),
                                module.getModuleCode(),
                                module.getParentId(),
                                module.getModuleUrl())
                );
                continue;
            }
            else
            {
                iteratorTree(module, root);
            }

        }
        return root;
    }


    /**
     * 将当前节点插入合适的菜单位置
     *
     * @param module 当前模块
     * @param treeModules 已计算的菜单
     */
    private void iteratorTree(SysModuleBean module, List<TreeModule> root)
    {

        for (TreeModule treeModule : root)
        {
            if(String.valueOf(treeModule.getRowId()).equals(module.getParentId()))
            {
                treeModule.setHasSub(true);
                treeModule.getChilds().add(new TreeModule(
                                module.getRowId(),
                                module.getModuleName(),
                                module.getModuleCode(),
                                module.getParentId(),
                                module.getModuleUrl())
                );
                break;
            }
            else
            {
                iteratorTree(module, treeModule.getChilds());
            }
        }
    }


    /**
     * 根据菜单首页url
     *
     * @param treeModules 菜单
     * @return String
     */
    private String getIndexUrl(List<TreeModule> treeModules)
    {
        if(!treeModules.isEmpty())
        {
            if(!treeModules.get(0).getChilds().isEmpty())
            {
                return getIndexUrl(treeModules.get(0).getChilds());
            }
            else
            {
                return treeModules.get(0).getModuleUrl();
            }
        }
        return "";
    }
}
